package com.itheima.ydd.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.ydd.dto.RoleDto;
import com.itheima.ydd.entity.Menu;
import com.itheima.ydd.entity.Role;
import com.itheima.ydd.entity.RoleMenu;
import com.itheima.ydd.mapper.RoleMapper;
import com.itheima.ydd.mapper.RoleMenuMapper;
import com.itheima.ydd.service.MenuService;
import com.itheima.ydd.service.RoleMenuService;
import com.itheima.ydd.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色表 服务实现类
 * </p>
 *
 * @author yan.zhou
 * @since 2022-02-22
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Autowired
    private RoleMenuService roleMenuService;
    @Autowired
    private RoleMenuMapper roleMenuMapper;

    @Override
    public List<String> roleNameList(String role_id) {
        String[] strings = role_id.split(",");
        LambdaQueryWrapper<Role> roleLambdaQueryWrapper = new LambdaQueryWrapper<>();
        roleLambdaQueryWrapper.in(Role::getId, strings);
        List<Role> roles = this.list(roleLambdaQueryWrapper);
        List<String> roleNameList = CollUtil.getFieldValues(roles, "name", String.class);
        return roleNameList;
    }

    //存入集合
    @Override
    public void saveWithRoleMenu(RoleDto roleDto) {
        super.save(roleDto);
        //存到集合
        List<RoleMenu> roleMenus = new LinkedList<>();
        List<Integer> menuIds = roleDto.getMenuids();
        for (Integer menuId : menuIds) {
            RoleMenu roleMenu = new RoleMenu();
            roleMenu.setRole_id(roleDto.getId());
            roleMenu.setMenu_id(menuId);
            roleMenus.add(roleMenu);
        }
        roleMenuService.saveBatch(roleMenus);
    }

    //修改
    @Override
    public void roleWithMenu(RoleDto roleDto) {
        this.updateById(roleDto);
        // 先根据roleId删除
        LambdaQueryWrapper<RoleMenu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RoleMenu::getRole_id, roleDto.getId());
        roleMenuService.remove(queryWrapper);


        // 按集合存储
        List<RoleMenu> roleMenus = new LinkedList<>();
        // List<RoleMenu> roleMenus = new ArrayList<>(roleDto.getMenuIds().size());

        for (Integer menuId : roleDto.getMenuids()) {
            RoleMenu roleMenu = new RoleMenu();
            roleMenu.setRole_id(roleDto.getId());
            roleMenu.setMenu_id(menuId);
            roleMenus.add(roleMenu);
        }
        roleMenuService.saveBatch(roleMenus);
    }
}
